﻿if (typeof Axis == "undefined") Axis = {};
if (typeof Axis.Admin == "undefined") Axis.Admin = {};
if (typeof Axis.Admin.Project == "undefined") Axis.Admin.Project = {};
if (typeof Axis.Admin.Project.Question == "undefined") Axis.Admin.Project.Question = {};
Axis.Admin.Project.Question.List = {
    Init: function () {
        var thisObj = this;
        thisObj.Grid.Init();
        var cmaskdate = new CMaskDate();
        cmaskdate.Init($("input[role=datepicker]"));
        var cdropdown = new CDropDownCheckList({ width: 200 });
        cdropdown.Init("#ddlFilter");
        var cdropdown2 = new CDropDownCheckList({ width: 200, maxDropHeight: 110, firstItemChecksAll: true, explicitClose: '<i>...close</i>' });
        cdropdown2.Init("[id$='ddlProvinceFilter'],[id$='ddlEducationFilter'],[id$='ddlClassFilter'],[id$='ddlMaritalStatusFilter'],[id$='ddlEducationFilter'],[id$='ddlJobFilter'],[id$='ddlTypeFilter'],[id$='ddlGenderFilter']");
        $("#UserFilter").hide();
        thisObj.Click();
        thisObj.Change();
    },
    Grid: {
        ID: "#UsersGrid",
        PagesID: "#UsersGridPages",
        GridObj: null,
        GridURL: 'Service/QuestionService.ashx?Action=GET',
        Init: function () {
            var thisObj = this;
            var options = {
                url: thisObj.GridURL,
                datatype: "json",
               
                colNames: [
                    'ID', 'STT', 'Mã câu hỏi','Nội dung', 'Loại câu', '','Max Res', 'Dự án', '', 'Status', '', 'Thao tác', '', '', '', '','','','','ContentType','MediaURL'
                ],
                colModel: [
                    { name: 'ID', index: 'ID', width: 50, hidden: true, frozen: true },
                    { name: 'STT', index: 'ID', width: 60, frozen: true, align: 'center' },
                    { name: 'Code', index: 'ID', width: 90, frozen: true, align: 'center' },
                    { name: 'Content', index: 'Content', width: 300, frozen: true },
                    { name: 'QuestionTypeText', index: 'QuestionType', width: 100, align: 'center' },

                    { name: 'QuestionType', index: 'Type', hidden: true },
                     { name: 'MaxResponseCount', index: 'MaxResponseCount',  width: 100, align: 'center'  },
                    { name: 'Project', index: 'ClassName', width: 170, align: 'center' },
                    { name: 'ProjectID', index: 'Class', hidden: true },
                    { name: 'StatusString', index: 'ScaleFrom', width: 90, align: 'center',hidden: true  },
                    { name: 'Status', index: 'ScaleFrom', width: 1, align: 'center',hidden: true  },
                    { name: 'Action', index: 'ScaleFrom', width: 90, align: 'center' },
                    { name: 'ScaleFrom', index: 'ScaleFrom', width: 1, align: 'center', hidden: true },
                    { name: 'ScaleFromText', index: 'EducationName', width: 1, align: 'center', hidden: true },
                    { name: 'ScaleTo', index: 'ScaleToText', width: 1, align: 'center', hidden: true },
                    { name: 'ScaleToText', index: 'ScaleToText', width: 1, align: 'center', hidden: true },
                    { name: 'DependentID', index: 'DependentID', width: 1, align: 'center', hidden: true },
                    { name: 'DisplayRandomResponse', index: 'DependentID', width: 1, align: 'center', hidden: true },
                     { name: 'DependentType', index: 'DependentType', width: 1, align: 'center', hidden: true },
                      { name: 'ContentType', index: 'ContentType', width: 1, align: 'center', hidden: true },
                     { name: 'MediaUrl', index: 'MediaURL', width: 1, align: 'center', hidden: true }
                ],
                onCellSelect: function (rowid, iCol, cellcontent, e) {
                },
                onSelectRow: function (rowid, status, e) {
                },
                ondblClickRow: function (rowid, iRow, iCol, e) {
                },
                afterInsertRow: function (rowid, aData, addData) {
                    var xA = '<img class="imgAction" src="Css/img/edit.png" id="PlaceOrder' + rowid + '" onclick="return ShowEdit(' + rowid + ')"/>';
                    $(thisObj.ID).setCell(rowid, 'Action', xA, {});

                },
                multiselect: true,
               // height: 'auto',
                rownumbers: true,
                autowidth: true,
                //forceFit: true,
               // shrinkToFit: false,
               // scroll: true,
                autoNumRow:false,
                rowNum: 250,
                pager: thisObj.PagesID,
                editurl: "Service/EditUser.ashx"
            };
            thisObj.GridObj = new CGrid(options);
            thisObj.GridObj.Init(thisObj.ID);
            thisObj.GridObj.NavGrid();
            thisObj.GridObj.FrozenColumns();
        },
        GetGridData: function () {
            return $(Axis.Admin.Project.Question.List.Grid.ID).jqGrid('getRowData');
        },
        Reload: function () {
            var thisObj = this;
            var newURL = thisObj.GridURL + "&ProjectID=" + $("#ddlProjectList").val();
            $(thisObj.ID).clearGridData();
            $(thisObj.ID).jqGrid('setGridParam', { url: newURL }).trigger("reloadGrid");
        },
        SelectRow: function () {
            var thisObj = this;
            if (thisObj.GridObj) {
                return thisObj.GridObj.SelectRow();
            }
            return null;
        }
    },
    DialogEdit: {
        ID: "#FormEdit",
        Dialog: null,
        Init: function (action, opts) {
            var thisObj = this;
            Axis.Admin.Project.Question.List.ClearForm();
            Axis.Admin.OptionAnswer.IndexRow=1;

            $("#cboDependent > option").remove();
           var listQuest=  Axis.Admin.Project.Question.List.Grid.GetGridData();
            $("#cboDependent").append( $.string.Format("<option value='{0}'>{1}</option>",0,''));
          
           if(opts==undefined)
             opts={ID:"-1"};
            $.each(listQuest, function(index,item){
             //console.log(opts.ID(opts.ID!=item.ID));
                             if(opts.ID==item.ID)
                    return false;
                 $("#cboDependent").append( $.string.Format("<option value='{0}'>{1}</option>",item.ID,item.Code));
            });
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Edit User",
                    width: 530
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
            var buttonText = "";
            switch (action) {
                case "INSERT":
                    thisObj.Dialog.SetTitle("Thêm câu hỏi");
                    $(thisObj.ID).find("[data-role='INSERT']").show();
                    buttonText = "Add";
                     $("#DisplayRandomResponse").removeAttr('checked');
                    break;
                case "UPDATE":
                    thisObj.Dialog.SetTitle("Hiệu chỉnh: " + "");
                     $("#DisplayRandomResponse").removeAttr('checked');
                    $.each(opts, function (key, value) {
                        $(thisObj.ID).find("[data-field=" + key + "]").val(value);
                    });
                     $("#DisplayRandomResponse").removeAttr('checked');
                    if(opts.DisplayRandomResponse=="1")
                    $("#DisplayRandomResponse").attr('checked','checked');
                    buttonText = "Cập nhật";
                    break;
            }
            var buttons = [
                        {
                            text: buttonText,
                            click: function (e) {
                             if( Axis.Admin.OptionAnswer.Update(action, opts))
                                thisObj.Close();
                            }
                        },
                        {
                            text: "Thoát",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

            ];
            $(thisObj.ID).dialog('option', 'buttons', buttons);
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        }
    },
    DialogFilter: {
        ID: "#UserFilter",
        Dialog: null,
        Init: function (type, opts) {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
            else {
                thisObj.Dialog = new CDialog({
                    title: "Filter",
                    width: 330,
                    height: 400,
                    buttons: [
                        {
                            text: "Search",
                            click: function (e) {
                                var data = {};
                                $("#UserFilter").find("input,select").each(function () {
                                    var $this = $(this);
                                    if ($this.attr("data-field")) {
                                        var key = $this.attr("data-field");
                                        var value = $this.val();
                                        if ($.isArray(value)) {
                                            data[key] = value.join(", ");
                                        }
                                        else {
                                            data[key] = value;
                                        }
                                    }
                                });
                                data = decodeURIComponent($.param(data));
                                $("#UsersGrid").jqGrid('setGridParam', { url: "Service/MemberService.ashx?Action=GET" + data, page: 1 }).trigger("reloadGrid");
                                thisObj.Close();
                            }
                        },
                        {
                            text: "Cancel",
                            click: function (e) {
                                thisObj.Close();
                            }
                        }

                    ]
                });
                thisObj.Dialog.Init(thisObj.ID);
            }
        },
        Open: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Open();
            }
        },
        Close: function () {
            var thisObj = this;
            if (thisObj.Dialog) {
                thisObj.Dialog.Close();
            }
        }
    },
    ClearForm: function () {
        $("#FormEdit").find("[data-field]").each(function () {
            var $this = $(this);
            $this.val("");
            if ($this.is("select")) {
                var value = $this.find("option[Default-Value='1']").attr("value");
                $this.val(value);
            }

        });
        $("#FormEdit").find("[data-role='INSERT']").hide();
    },
    Update: function (type, opts) {       
        var thisObj = this;    
                var data = {};       
            $("#FormEdit").find("input,select").each(function () {
                var $this = $(this);
                if ($this.attr("data-field")) {
                    var key = $this.attr("data-field");
                }
            });
           if(type== "DELETE")
                data.ID = opts.ID;
        data.ProjectID=$("#ddlProjectList").val();       
        data.Action = type;
        data.oper = type.toLowerCase();
        if(typeof USER_ID!="undefined"){
          data.UserID = USER_ID;
           data.SecrectToken = SECRECT_TOKEN;
        }

        $.Ajax({
            url: 'Service/QuestionService.ashx',
            type: 'POST',
            data: data,
            success: function (data, textStatus, jqXHR) {
                if (data) {
                    data = eval("(" + data + ")");
                    if (data.IsSuccessfull) {
                        Axis.Admin.Project.Question.List.Grid.Reload();
                    }
                }
            },
            beforeSend: function (jqXHR, settings) {
            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    },

    GetMaxOrderQuestion: function () {
        var objData = Axis.Admin.Project.Question.List.Grid.GetGridData();
      return objData.length+1;
    },
    Click: function () {
        var thisObj = this;
        $("#imgUserAdd").click(function () {
            thisObj.DialogEdit.Init("INSERT");
            var MaxQuestion = Axis.Admin.Project.Question.List.GetMaxOrderQuestion()*10;
            $("#txtZOrder").val(MaxQuestion);
            $("#ID").val(0);
             Axis.Admin.OptionAnswer.IndexRow=1;
            Axis.Admin.OptionAnswer.GenarateListOption();
        });
        $("#imgUserEdit").click(function () {
            var rowData = thisObj.Grid.SelectRow();
            if (rowData && rowData.ID)
                thisObj.DialogEdit.Init("UPDATE", rowData);
            else alert("Please Select Row");
        });
        $("#imgUserFilter").click(function () {
            thisObj.DialogFilter.Init();

        });
        $("#imgUserDel").click(function () {
            var rowData = thisObj.Grid.SelectRow();
            if (rowData && rowData.ID) {
                $.CAlert.Confirm({
                    Title: "Xóa câu hỏi",
                    Content: $.string.Format("Bạn có chắc muốn  câu hỏi: [{0}].", rowData.Code)
                }, function (isOK) {
                    if (isOK)
                        thisObj.Update("DELETE", rowData);
                });
            }
            else {
                $.CAlert.Alert({
                    Title: "Xóa câu hỏi",
                    Content: "Vui lòng chọn câu hỏi cần xóa."
                });
            }
        });
    },
    Change:function(){
        var thisObj = this;
        $("#ddlProjectList").bind("change", function () {
            thisObj.Grid.Reload();
        }).trigger("change");
        $("#ddlQuestionType").bind("change", function () {
           GenarateListOption(this);
        }).trigger("change");
    },
};
$(function () {
    Axis.Admin.Project.Question.List.Init();
    $("#ddlProjectList").bind('change',function(){
    ReloadGrid();
    });

    window.setTimeout(function(){
    $("#ddlProjectList").val(62);
     ReloadGrid();},1000);
});

function ReloadGrid() {
    Axis.Admin.Project.Question.List.Grid.Reload();
}
function ShowEdit(rowID) {
    var thisObj = Axis.Admin.Project.Question.List;
    var rowData = $(thisObj.Grid.ID).jqGrid('getRowData', rowID);
    if (rowData && rowData.ID) {
        thisObj.DialogEdit.Init("UPDATE", rowData);
        Axis.Admin.OptionAnswer.GetListOption(rowData);
    }
}